﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenSearch.Client;
using OpenSearch.Controls;
using SpicIE.Parameter;

namespace OpenSearch.Bho
{
    public partial class IeOpenSearchToolbar : SpicIE.Controls.Toolbar
    {
        public const string Plugin_Guid = "06315005-7584-4750-B413-D7EA0F8A618B";
        public const string Plugin_ProgId = "OpenSearch.IEToolbar";

        private SearchBox _searchBox;

        public static IeOpenSearchToolbar ToolbarInstance;

        public IeOpenSearchToolbar()
        {
            // This component gets created twice -- once by COM, then by the force show of the BHO

            InitializeComponent();

            _searchBox = new SearchBox();

            if (ToolbarInstance != null)
            {
                // Use the existing search manager
                _searchBox.SearchManager = ToolbarInstance._searchBox.SearchManager;
            }
            else
            { 
                _searchBox.SearchManager = new SearchClientManager(); 
            }

            ToolbarInstance = this;

            elementHost1.Child = _searchBox;

            ToolbarHelpText = "OpenSearch Toolbar";
            ToolbarName = "OpenSearch Toolbar";
            ToolbarTitle = "OpenSearch Toolbar";

            ToolbarStyle = ToolbarEnum.ExplorerToolbar;

            MinSize = new Size(50, 25);

            _searchBox.SearchRequested += SearchBox_SearchRequested;

            if (IeBho.HostInstance != null)
            {
                IeBho.HostInstance.OnDocumentComplete += HostInstance_OnDocumentComplete;
            }
        }

        void HostInstance_OnDocumentComplete(object pDisp, ref object Url)
        {
            string url = (string)Url;

            Uri uri;
            if (Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                _searchBox.CurrentPageUri = uri;
            }
        }

        private void SearchBox_SearchRequested(object sender, SearchRequestedEventArgs e)
        {
            if (e.NewWindow)
                IeBho.HostInstance.BrowserRef.Navigate(e.SearchAddress.ToString(), TargetFrameName: "_blank");
            else
                IeBho.HostInstance.BrowserRef.Navigate(e.SearchAddress.ToString());
        }
        
        public override string PluginGuid
        {
            get
            {
                return Plugin_Guid;
            }
        }

        public override string PluginProgID
        {
            get
            {
                return Plugin_ProgId;
            }
        }
    }
}
